<?php

class Chat_model extends CI_Model {
	public function __construct() {
		parent::__construct();
	}

	public function queryMsg($toId = FALSE) {
		if (!$toId) {
			return array();
		}
		$query = $this->db
		              ->select('fromId, fromName, toId, time, text')
		              ->from('messages_unread')
		              ->where('toId', $toId)
		              ->order_by('id', 'asc')
		              ->get()
		              ->result_array();
		if (count($query) < 1) {
			return FALSE;
		}
		return $query;
	}

	public function confirmMsg($msgs = FALSE) {
		if (!$msgs) {
			return FALSE;
		}
		foreach ($msgs as $msg) {
			$this->db
			     ->insert('messages_read', $msg);
			$this->db
			     ->delete('messages_unread', $msg);
		}
		return TRUE;
	}
	//$msgData contains fromId, toId, text
	public function sendToUser($msgData = FALSE) {
		if (!$msgData) {
			return FALSE;
		}
		$this->db
		     ->insert('messages_unread', $msgData);
		return TRUE;
	}

	public function sendToGroup($msgData = FALSE) {
		if (!$msgData) {
			return FALSE;
		}
		$groupId = $msgData['toId'];
		$queryUser = $this->db
		                  ->select('userId')
		                  ->from('group_user')
		                  ->where('groupId', $groupId)
		                  ->get()
		                  ->result_array();
		foreach ($queryUser as $user) {
			if ($user['userId'] != $msgData['fromId']) {
				$msgData['toId'] = $user['userId'];
				$this->sendToUser($msgData);
			}
		}
		return TRUE;
	}

	public function sendToSelf($msgData = FALSE) {
		if (!$msgData) {
			return FALSE;
		}
		$this->db
		     ->insert('messages_unread', array(
			     'fromId' => $msgData['fromId'],
			     'toId' => $msgData['fromId'],
			     'time' => $msgData['time'],
			     'text' => $msgData['text'],
		     ));
		return TRUE;
	}

}